// 分布式定时任务管理系统前端脚本

$(document).ready(function() {
    // 初始化页面
    loadSystemInfo();
    
    // 每30秒刷新一次系统信息
    setInterval(loadSystemInfo, 30000);
});

// 显示指定页面
function showPage(pageId) {
    // 隐藏所有页面
    $('.page-content').hide();
    
    // 移除所有导航链接的激活状态
    $('.sidebar .nav-link').removeClass('active');
    
    // 显示指定页面
    $('#' + pageId + '-page').show();
    
    // 激活当前导航链接
    $('a[onclick="showPage(\'' + pageId + '\')"]').addClass('active');
    
    // 根据页面类型加载数据
    switch(pageId) {
        case 'dashboard':
            loadSystemInfo();
            break;
        case 'jobs':
            loadJobs();
            break;
        case 'logs':
            loadLogs();
            break;
        case 'cluster':
            loadClusterNodes();
            break;
    }
}

// 加载系统信息
function loadSystemInfo() {
    $.ajax({
        url: '/api/system/info',
        method: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const data = response.data;
                $('#active-nodes-count').text(data.activeNodes || 0);
                $('#total-jobs-count').text(data.totalJobs || 0);
                $('#running-jobs-count').text(data.runningJobs || 0);
            }
        },
        error: function() {
            console.error('Failed to load system info');
        }
    });
}

// 加载任务列表
function loadJobs() {
    $.ajax({
        url: '/api/jobs',
        method: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const jobs = response.data;
                let html = '';
                
                jobs.forEach(function(job) {
                    const statusBadge = getStatusBadge(job.jobStatus);
                    const triggerBadge = getTriggerStatusBadge(job.triggerStatus);
                    
                    html += `
                        <tr>
                            <td>${job.id}</td>
                            <td>${job.jobDesc}</td>
                            <td>${job.jobCron}</td>
                            <td>${job.jobClassName}</td>
                            <td>${statusBadge}</td>
                            <td>${triggerBadge}</td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button class="btn btn-info btn-sm" onclick="editJob(${job.id})">
                                        <i class="fa fa-edit"></i> 编辑
                                    </button>
                                    <button class="btn btn-${job.triggerStatus === 1 ? 'warning' : 'success'} btn-sm" 
                                            onclick="toggleJobStatus(${job.id}, ${job.triggerStatus})">
                                        <i class="fa fa-${job.triggerStatus === 1 ? 'pause' : 'play'}"></i> 
                                        ${job.triggerStatus === 1 ? '停止' : '启动'}
                                    </button>
                                    <button class="btn btn-danger btn-sm" onclick="deleteJob(${job.id})">
                                        <i class="fa fa-trash"></i> 删除
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                });
                
                $('#jobs-table-body').html(html);
            }
        },
        error: function() {
            showAlert('加载任务列表失败', 'danger');
        }
    });
}

// 加载执行日志
function loadLogs() {
    $.ajax({
        url: '/api/logs',
        method: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const logs = response.data;
                let html = '';
                
                logs.forEach(function(log) {
                    const triggerStatus = log.triggerCode === 200 ? 'success' : 'danger';
                    const handleStatus = log.handleCode === 200 ? 'success' : 
                                        log.handleCode === 0 ? 'warning' : 'danger';
                    
                    html += `
                        <tr>
                            <td>${log.id}</td>
                            <td>${log.jobId}</td>
                            <td>${log.executorAddress || '-'}</td>
                            <td>${formatDateTime(log.triggerTime)}</td>
                            <td>${log.handleTime ? formatDateTime(log.handleTime) : '-'}</td>
                            <td><span class="badge badge-${triggerStatus}">${log.triggerCode}</span></td>
                            <td><span class="badge badge-${handleStatus}">${log.handleCode}</span></td>
                            <td>${log.handleMsg || '-'}</td>
                        </tr>
                    `;
                });
                
                $('#logs-table-body').html(html);
            }
        },
        error: function() {
            showAlert('加载执行日志失败', 'danger');
        }
    });
}

// 加载集群节点
function loadClusterNodes() {
    $.ajax({
        url: '/api/cluster/nodes',
        method: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const nodes = response.data;
                let html = '';
                
                nodes.forEach(function(node) {
                    const isActive = isNodeActive(node.updateTime);
                    const statusBadge = isActive ? 
                        '<span class="badge badge-success">活跃</span>' : 
                        '<span class="badge badge-danger">离线</span>';
                    
                    html += `
                        <tr>
                            <td>${node.registryKey}</td>
                            <td>${node.registryValue}</td>
                            <td>${formatDateTime(node.updateTime)}</td>
                            <td>${statusBadge}</td>
                        </tr>
                    `;
                });
                
                $('#cluster-table-body').html(html);
            }
        },
        error: function() {
            showAlert('加载集群节点失败', 'danger');
        }
    });
}

// 显示新增任务模态框
function showAddJobModal() {
    $('#jobModalTitle').text('新增任务');
    $('#jobForm')[0].reset();
    $('#jobId').val('');
    $('#jobModal').modal('show');
}

// 编辑任务
function editJob(jobId) {
    $.ajax({
        url: '/api/jobs/' + jobId,
        method: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const job = response.data;
                $('#jobModalTitle').text('编辑任务');
                $('#jobId').val(job.id);
                $('#jobDesc').val(job.jobDesc);
                $('#jobCron').val(job.jobCron);
                $('#jobClassName').val(job.jobClassName);
                $('#jobParam').val(job.jobParam);
                $('#jobGroup').val(job.jobGroup);
                $('#author').val(job.author);
                $('#alarmEmail').val(job.alarmEmail);
                $('#executorFailRetryCount').val(job.executorFailRetryCount);
                $('#executorTimeout').val(job.executorTimeout);
                $('#jobModal').modal('show');
            }
        },
        error: function() {
            showAlert('加载任务详情失败', 'danger');
        }
    });
}

// 保存任务
function saveJob() {
    const jobId = $('#jobId').val();
    const isEdit = jobId !== '';
    
    const jobData = {
        id: jobId || null,
        jobDesc: $('#jobDesc').val(),
        jobCron: $('#jobCron').val(),
        jobClassName: $('#jobClassName').val(),
        jobParam: $('#jobParam').val(),
        jobGroup: $('#jobGroup').val(),
        author: $('#author').val(),
        alarmEmail: $('#alarmEmail').val(),
        executorFailRetryCount: parseInt($('#executorFailRetryCount').val()),
        executorTimeout: parseInt($('#executorTimeout').val())
    };
    
    const url = isEdit ? '/api/jobs/' + jobId : '/api/jobs';
    const method = isEdit ? 'PUT' : 'POST';
    
    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(jobData),
        success: function(response) {
            if (response.code === 200) {
                $('#jobModal').modal('hide');
                showAlert(isEdit ? '任务更新成功' : '任务创建成功', 'success');
                loadJobs();
            } else {
                showAlert(response.msg || '保存失败', 'danger');
            }
        },
        error: function() {
            showAlert('保存任务失败', 'danger');
        }
    });
}

// 切换任务状态
function toggleJobStatus(jobId, currentStatus) {
    const action = currentStatus === 1 ? 'stop' : 'start';
    const actionText = currentStatus === 1 ? '停止' : '启动';
    
    if (!confirm(`确定要${actionText}任务吗？`)) {
        return;
    }
    
    $.ajax({
        url: `/api/jobs/${jobId}/${action}`,
        method: 'POST',
        success: function(response) {
            if (response.code === 200) {
                showAlert(`任务${actionText}成功`, 'success');
                loadJobs();
            } else {
                showAlert(response.msg || `${actionText}失败`, 'danger');
            }
        },
        error: function() {
            showAlert(`${actionText}任务失败`, 'danger');
        }
    });
}

// 删除任务
function deleteJob(jobId) {
    if (!confirm('确定要删除此任务吗？删除后不可恢复！')) {
        return;
    }
    
    $.ajax({
        url: '/api/jobs/' + jobId,
        method: 'DELETE',
        success: function(response) {
            if (response.code === 200) {
                showAlert('任务删除成功', 'success');
                loadJobs();
            } else {
                showAlert(response.msg || '删除失败', 'danger');
            }
        },
        error: function() {
            showAlert('删除任务失败', 'danger');
        }
    });
}

// 获取状态徽章
function getStatusBadge(status) {
    if (status === 1) {
        return '<span class="status-badge status-running">启用</span>';
    } else {
        return '<span class="status-badge status-disabled">禁用</span>';
    }
}

// 获取触发状态徽章
function getTriggerStatusBadge(status) {
    if (status === 1) {
        return '<span class="status-badge status-running">运行中</span>';
    } else {
        return '<span class="status-badge status-stopped">已停止</span>';
    }
}

// 判断节点是否活跃
function isNodeActive(updateTime) {
    const now = new Date().getTime();
    const updateTimeMs = new Date(updateTime).getTime();
    return (now - updateTimeMs) < 90000; // 90秒内更新过认为是活跃的
}

// 格式化日期时间
function formatDateTime(dateTime) {
    if (!dateTime) return '-';
    const date = new Date(dateTime);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0') + ' ' +
           String(date.getHours()).padStart(2, '0') + ':' + 
           String(date.getMinutes()).padStart(2, '0') + ':' + 
           String(date.getSeconds()).padStart(2, '0');
}

// 显示提示消息
function showAlert(message, type) {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    `;
    
    // 移除现有的提示
    $('.alert').remove();
    
    // 添加新提示到页面顶部
    $('.content').prepend(alertHtml);
    
    // 3秒后自动关闭
    setTimeout(function() {
        $('.alert').fadeOut();
    }, 3000);
}